package fw.ssh.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import fw.ssh.entity.User;
import fw.ssh.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("/user/index")
	public String index() {

		return "index";

	}

	@RequestMapping("/user/add")
	public String add(String name, String password, Model model) {
		try {
			userService.add(name, password);

			model.addAttribute("msg", "Add user " + name + " success!");
			return "success";
		} catch (Exception ex) {
			return "failed";
		}
	}

	@RequestMapping("/user/login")
	public String login(User user, Model model) {
		Optional<User> found = userService.find(user);

		if (found.isPresent()) {
			model.addAttribute("msg", "Welcome back " + found.get().getName());
			return "success";
		} else {
			return "failed";
		}
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
